package com.samphanie.auiu.admin.controller;

import com.samphanie.auiu.admin.domain.dto.MenuDto;
import com.samphanie.auiu.admin.service.ISysMenuService;
import com.samphanie.auiu.common.utils.ApiResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.val;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 菜单Controller
 *
 * @author zsy
 * @date 2021-05-18
 */
@Api(tags = "菜单模块")
@RestController
@RequestMapping("/admin/menu")
@RequiredArgsConstructor
public class SysMenuController {

    private final ISysMenuService sysMenuService;

    /**
     * 查询菜单列表
     */
    @ApiOperation("菜单列表")
    @GetMapping("/list")
    public ApiResponse<?> list(@RequestParam Map<String, Object> query) {
        return ApiResponse.success(sysMenuService.listPage(query));
    }

    @ApiOperation("树形菜单列表")
    @GetMapping("/get")
    public ApiResponse<?> get() {
        return ApiResponse.success(sysMenuService.treeMenuList());
    }

    @ApiOperation("用户的树形菜单列表")
    @GetMapping("/get/{userId}")
    public ApiResponse<?> getUserTreeMenuList(@PathVariable("userId") Long userId) {
        return ApiResponse.success(sysMenuService.getUserTreeMenuList(userId));
    }

    @ApiOperation("用户菜单列表")
    @GetMapping("/nav/{userId}")
    public ApiResponse<?> getUserMenuList(@PathVariable("userId") Long userId) {
        return ApiResponse.success(sysMenuService.getUserMenuList(userId));
    }


    /**
     * 获取菜单详细信息
     */
    @ApiOperation("菜单详情")
    @GetMapping(value = "/{id}")
    public ApiResponse<?> getInfo(@PathVariable("id") Long id) {
        return ApiResponse.success(sysMenuService.getById(id));
    }

    /**
     * 新增菜单
     */
    @ApiOperation("新增菜单")
    @PostMapping("/add")
    public ApiResponse<?> add(@Valid @RequestBody MenuDto menuDto) {
        boolean result = sysMenuService.createMenu(menuDto);
        return ApiResponse.success(result);
    }

    /**
     * 修改菜单
     */
    @ApiOperation("编辑菜单")
    @PutMapping("/edit")
    public ApiResponse<?> edit(@RequestBody MenuDto menuDto) {
        boolean result = sysMenuService.edit(menuDto);
        return ApiResponse.success(result);
    }

    /**
     * 删除菜单
     */
    @ApiOperation("删除菜单")
    @DeleteMapping("/delete")
    public ApiResponse<?> remove(@RequestBody Long[] ids) {

        val longs = Arrays.asList(ids);
        val delIds = longs.stream().filter(item -> !sysMenuService.checkHasSubMenu(item)).collect(Collectors.toList());

        // TODO 判断是否属于系统菜单
        // 判断是否有子菜单
        // boolean check = sysMenuService.checkHasSubMenu(menuId);
        //        if (check) {
        //            return ApiResponse.failed("请先删除子菜单");
        //        }
        sysMenuService.removeByIds(delIds);
        // TODO 删除菜单对应的资源 和 权限
        return ApiResponse.success("删除成功");
    }
}
